<template>
  <div class="container">
    <!-- 状态筛选模块 -->
    <div class="status-filter" style="padding-bottom: 10px">
      <el-button class="button_all" :type="data.buttonAll_type" @click="selectAll">
        全部订单
      </el-button>
      <el-button
          v-for="(status, key) in statusMap"
          :key="key"
          :type="key === data.selectedStatus ? 'primary' : ''"
          @click="data.selectedStatus = key; select(key)"
      >
        {{ status }}
      </el-button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
          v-model="data.search_info"
          placeholder="搜索商品名称/订单号"
          class="search-input"
          clearable
      >
        <template #prefix>
          <el-icon>
            <Search />
          </el-icon>
        </template>
      </el-input>
      <el-button type="primary" size="large" class="search-btn" @click="load">
        搜索订单
      </el-button>
    </div>

    <!-- 订单卡片列表 -->
    <div class="order-list">
      <div
          v-for="(item, index) in data.tableData"
          :key="index"
          class="order-card"
      >
        <!-- 订单头部 -->
        <div class="order-header">
          <span class="order-time">{{ item.createTime }}</span>
          <div class="shop_infor">
            <img :src="item.avatar" alt="头像" style="width: 10%; padding-right: 10px" />
            <span>{{ item.shop_name }}</span>
          </div>
          <span class="order-status">{{ getStatusName(item.status) }}</span>
        </div>

        <!-- 订单主体 -->
        <div class="order-body">
          <!-- 商品信息 -->
          <div class="product-info">
            <img :src="item.image" alt="商品图片" class="product-image" />
            <div class="product-details">
              <div class="product-title">{{ item.title }}</div>
              <div class="product-sellPoint">{{ item.sellPoint }}</div>
              <div class="product-sku">订单号：{{ item.orderNo }}</div>
              <div class="product-price">
                实付款：<span class="price">¥{{ item.payPrice }}</span>
              </div>
            </div>
          </div>
          <!-- 评价信息 -->
          <div v-if="item.comment" class="comment-section">
            <div class="comment-header">
              <span class="comment-title">我的评价：</span>
              <el-rate v-model="item.comment.rating" disabled></el-rate>
            </div>
            <div class="comment-content">{{ item.comment.content }}</div>
            <div class="comment-time">评价时间：{{ item.comment.reviewTime }}</div>
          </div>
          <!-- 操作按钮 -->
          <div class="action-btns">
            <div class="left-btns">
              <el-button
                  v-if="item.status === 1"
                  type="primary"
                  plain
                  @click="cancleOrder(item)"
                  class="action-btn"
              >
                取消订单
              </el-button>
            </div>

            <div class="right-btns">
              <el-button
                  v-if="item.status === 1"
                  type="danger"
                  plain
                  class="action-btn"
                  @click="payOrder(item)"
              >
                立即支付
              </el-button>

              <el-button
                  v-if="item.status === 2 || item.status === 3"
                  type="success"
                  plain
                  class="action-btn"
                  @click="sureGot(item)"
              >
                确认收货
              </el-button>

              <el-button
                  v-if="item.status === 3"
                  type="info"
                  plain
                  class="action-btn"
                  @click="applyRefund(item)"
              >
                申请退款
              </el-button>

              <el-button
                  v-if="item.status === 5"
                  type="warning"
                  plain
                  class="action-btn"
                  @click="cancelRefund(item)"
              >
                取消退款
              </el-button>

              <el-button
                  v-if="item.status === 4 && !item.comment"
                  type="primary"
                  plain
                  class="action-btn"
                  @click="openCommentDialog(item)"
              >
                评价
              </el-button>
            </div>
          </div>
        </div>


      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="data.currentPage"
          v-model:page-size="data.pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="data.total"
          @size-change="load"
          @current-change="load"
      />
    </div>

    <!-- 评价对话框 -->
    <el-dialog
        v-model="data.commentDialogVisible"
        title="评价订单"
        width="500px"
    >
      <el-form :model="data.commentForm" label-width="80px">
        <el-form-item label="评分">
          <el-rate allow-half v-model="data.commentForm.rating"></el-rate>
        </el-form-item>
        <el-form-item label="评价内容">
          <el-input
              v-model="data.commentForm.content"
              type="textarea"
              :rows="4"
              placeholder="请输入评价内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="上传图片">
          <el-upload
              action="http://localhost:8080/files/upload/reviewImage"
              list-type="picture-card"
              :show-file-list="true"
              :on-success="handleUploadSuccess"
              :limit="1"
          >
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="data.commentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitComment">提交评价</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {reactive} from "vue";
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";

const data = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  search_info: "",
  tableData: [],
  user: JSON.parse(localStorage.getItem("user_information")) || {},
  selectedStatus: 0,
  buttonAll_type: "default",
  commentDialogVisible: false, // 评价对话框显示状态
  commentForm: {
    orderNo: "",
    rating: 0,
    content: "",
    reviewImage: "",
  },
});

const openCommentDialog = (item) => {
  data.commentForm.orderNo = item.orderNo;
  data.commentDialogVisible = true;
};

const selectAll = () => {
  load();
  data.selectedStatus = 0;
  data.buttonAll_type = "primary";
};

//取消订单
const cancleOrder = (item) => {
  ElMessageBox.confirm("取消订单后无法恢复，是否取消", '取消', {type: 'warning'}).then(() => {
    request.get("/order/selectByNo/" + item.orderNo).then(res => {
      if (res.code === 200) {
        data.order = res.data;
        data.order.status = 7;
        request.post("/order/updateStatus", data.order).then(res => {
          if (res.code === 200) {
            ElMessage.success("订单已取消")
            load()
          }
        })
      } else {
        ElMessage.error("订单无法取消")
      }
    })
  })
}
//支付
const payOrder = (item) => {
  ElMessageBox.confirm("确认支付", "确认", {type: 'success'}).then(() => {
    request.get("/order/selectByNo/" + item.orderNo).then(res => {
      if (res.code === 200) {
        data.order = res.data;
        data.order.status = 2;
        request.post("/order/updatePayTime", data.order).then(res => {
          if (res.code === 200) {
            ElMessage.success("订单已支付")
            load()
          }
        })
      } else {
        ElMessage.error("支付失败")
      }
    })
  })
}

//确认收获
const sureGot = (item) => {
  ElMessageBox.confirm("确认收获", "确认", {type: 'success'}).then(() => {
    request.get("/order/selectByNo/" + item.orderNo).then(res => {
      if (res.code === 200) {
        data.order = res.data;
        data.order.status = 4;
        request.post("/order/updateEndTime", data.order).then(res => {
          if (res.code === 200) {
            ElMessage.success("已确认收获")
            load()
          }
        })
      } else {
        ElMessage.error("无法确认")
      }
    })
  })
}

//申请退款
const applyRefund = (item) => {
  ElMessageBox.confirm("是否申请退款", "确认", {type: 'warning'}).then(() => {
    request.get("/order/selectByNo/" + item.orderNo).then(res => {
      if (res.code === 200) {
        data.order = res.data;
        data.order.oldStatus = item.status;
        data.order.status = 5;
        request.post("/order/updateStatus", data.order).then(res => {
          if (res.code === 200) {
            ElMessage.success("已申请退款，请等待商家确认")
            load()
          }
        })
      } else {
        ElMessage.error("无法申请退款")
      }
    })
  })
}

const select = async (key) => {
  try {
    const response = await request.get("/order/selectPageByUserAndStatus", {
      params: {
        currentPage: data.currentPage,
        pageSize: data.pageSize,
        id: data.user.userId,
        status: key,
      },
    });

    if (response.code === 200) {
      data.total = response.data.total;
      data.tableData = response.data.list;

      // 为每个订单加载评价信息
      for (const item of data.tableData) {
        const reviewResponse = await request.get("/review/getByOrderNo", {
          params: {
            orderNo: item.orderNo,
          },
        });

        if (reviewResponse.code === 200) {
          item.comment = reviewResponse.data; // 绑定评价信息
        } else {
          item.comment = null; // 如果没有评价信息，设置为 null
        }
      }
    } else {
      throw new Error("获取订单数据失败，服务器返回错误代码：" + response.code);
    }
  } catch (error) {
    console.error("加载订单数据失败:", error);
    ElMessage.error("加载订单数据失败：" + error.message);
  }
};

//取消退款
const cancelRefund = (item) => {
  ElMessageBox.confirm("是否取消退款申请", "确认", {type: 'warning'}).then(() => {
    request.get("/order/selectByNo/" + item.orderNo).then(res => {
      if (res.code === 200) {
        data.order = res.data;
        data.order.status = data.order.oldStatus;
        request.post("/order/updateStatus", data.order).then(res => {
          if (res.code === 200) {
            ElMessage.success("申请已取消")
            load()
          }
        })
      } else {
        ElMessage.error("无法取消退款！")
      }
    })
  })
}

const load = async () => {
  try {
    const orderResponse = await request.get("/order/selectPageByuser", {
      params: {
        currentPage: data.currentPage,
        pageSize: data.pageSize,
        id: data.user.userId,
      },
    });

    if (orderResponse.code === 200) {
      data.total = orderResponse.data.total;
      data.tableData = orderResponse.data.list;

      for (const item of data.tableData) {
        const reviewResponse = await request.get("/review/getByOrderNo", {
          params: {
            orderNo: item.orderNo,
          },
        });

        if (reviewResponse.code === 200) {
          item.comment = reviewResponse.data;
        } else {
          item.comment = null;
        }
      }
    }
  } catch (error) {
    console.error("加载数据失败:", error);
    ElMessage.error("加载数据失败");
  }
};

const submitComment = async () => {
  try {
    const addResponse = await request.post("/review/add", data.commentForm);
    if (addResponse.code !== 200) {
      throw new Error("评价提交失败");
    }

    const orderNo = data.commentForm.orderNo;
    const selectResponse = await request.get("/order/selectByNo/" + orderNo);
    if (selectResponse.code !== 200) {
      throw new Error("获取订单信息失败");
    }

    data.order = selectResponse.data;
    data.order.status = 8;
    const updateResponse = await request.post("/order/updateStatus", data.order);
    if (updateResponse.code !== 200) {
      throw new Error("更新订单状态失败");
    }

    ElMessage.success("评价成功");
    data.commentDialogVisible = false;
    load();
  } catch (error) {
    ElMessage.error(error.message || "评价失败");
  }
};

const statusMap = {
  1: "待支付",
  2: "待发货",
  3: "待收货",
  4: "待评价",
  5: "待退款",
  6: "已退款",
  7: "已取消",
  8: "完成",
};

const getStatusName = (status) => statusMap[status] || "未知状态";

const handleUploadSuccess = (response, file) => {
  data.commentForm.reviewImage = response.data;
  ElMessage.success("图片上传成功");
};

load();
</script>

<style scoped>
.container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 4px;
}

.search-input {
  flex: 1;
  max-width: 400px;
}

.order-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.order-card {
  background: white;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.order-header {
  display: flex;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
  margin-bottom: 16px;
  font-size: 14px;
  color: #666;
}

.shop_infor {
  display: flex;
  font-size: 18px;
  padding: 0 34px;
  color: #eecd00;
}

.order-body {
  display: flex;
  gap: 20px;
  margin-bottom: 16px;
}

.product-info {
  display: flex;
  gap: 10px;
  flex: 1;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  border: 1px solid #eee;
}

.product-details {
  flex: 1;
}

.comment-section {
  flex: 1;
  margin-left: 20px;
  padding: 16px;
  background: #f9f9f9;
  border-radius: 4px;
  border: 1px solid #eee;
}

.action-btns {
  display: flex;
  justify-content: space-between;
  gap: 10px;
  min-width: 150px;
  padding-right: 50px;
}

.left-btns,
.right-btns {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.action-btn {
  padding: 8px 12px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  background: white;
  padding: 16px;
  border-radius: 4px;
}

@media (max-width: 768px) {
  .order-body {
    flex-direction: column;
  }

  .action-btns {
    flex-direction: row;
    justify-content: flex-end;
  }
}
</style>